package com.efounder.chat.activity;

import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.fragment.app.FragmentTransaction;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.efounder.chat.R;
import com.efounder.chat.adapter.ChatAdapter;
import com.efounder.chat.adapter.ChatVoicePlayClickListener;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.NotifyChatUIRefreshEvent;
import com.efounder.chat.fragment.ChatOfficialAccountsSenderFragment;
import com.efounder.chat.fragment.ChatOfficialAccountsSenderFragment.OnOfficialAccountKyeboardClickListener;
import com.efounder.chat.fragment.ChatSenderFragment;
import com.efounder.chat.fragment.ChatSenderFragment.OnClickMessageEditTextListener;
import com.efounder.chat.fragment.ChatSenderFragment.OnVoiceRecordListener;
import com.efounder.chat.fragment.ChatSenderFragment.SendMessageCallback;
import com.efounder.chat.handler.ChatMessageListener;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.listener.OnTouchListViewListener;
import com.efounder.chat.manager.ChatListManager;
import com.efounder.chat.manager.ChatMessageSendManager;
import com.efounder.chat.manager.ChatVoiceRecordAnimManager;
import com.efounder.chat.model.Group;
import com.efounder.chat.model.GroupRootBean;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.service.MessageService;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatConfigUtil;
import com.efounder.chat.utils.GroupAvatarHelper;
import com.efounder.chat.utils.GroupAvatarUtil;
import com.efounder.chat.utils.TextFormatMessageUtil;
import com.efounder.chat.widget.ChatListView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.message.manager.JFMessageListener;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.router.constant.RouterConstant;
import com.efounder.utils.ResStringUtil;
import com.groupimageview.NineGridImageView;
import com.pansoft.library.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;


/**
 * 聊天Activity
 *
 * @author hudq
 */
@Deprecated
@SuppressLint("ClickableViewAccessibility")
@Route(path = RouterConstant.CHAT_INPUT_MESSAGE_OLD)
public class ChatActivity extends BaseActivity implements
        OnVoiceRecordListener, OnClickMessageEditTextListener,
        SendMessageCallback, OnOfficialAccountKyeboardClickListener,
        MessageService.MessageServiceNetStateListener, MessageService.MessageServiceLoginListener, ChatSenderFragment.PreSendMessageCallback, OnClickListener {
    public static final String TAG = "ChatActivity";

    private ChatSenderFragment chatSenderFragment;
    private ChatOfficialAccountsSenderFragment chatOfficialAccountsSenderFragment;
    /**
     * 语音容器（语音时显示在中间的麦克风容器）
     **/
    private View recordingContainer;
    /**
     * 麦克风图片
     **/
    private ImageView micImage;
    /**
     * 语音时 “手指上滑，取消发送” 提示
     **/
    private TextView recordingHint;
    /**
     * 聊天ListView
     **/
    private ChatListView chatListView;
    /**
     * 聊天ListView 的 adapter
     **/
    private ChatAdapter chatAdapter;
    /**
     * 聊天类型：判断单聊，还是群聊，还是公众号
     **/
    private byte chatType;
    public ChatActivity activityInstance = null;
    /**
     * 聊天对象id
     **/
    private int id;
    private Group group;
    /**
     * 下拉加载更多（转圈圈）
     **/
    private ProgressBar loadmorePB;
    public String playMsgId;

    String toUserNick = "";
    // 设置按钮
    private ImageView iv_setting;
    private ImageView iv_setting_group;
    /**
     * 左上角显示的用户名称
     **/
    private TextView toChatUserNickTextView;

    private User user;
    /**
     * 消息管理器
     **/
    private JFMessageManager messageManager;
    /**
     * 消息监听
     **/
    private JFMessageListener messageListener;
    //listview的onTouch监听
    private OnTouchListViewListener onTouchListViewListener;

    private Handler messageHandler = new MessageHandler(this);
    List<IMStruct002> messageList;//消息记录
    //使用targetList来作为一个缓冲的list存储messageList的数据变化，刷新ListView，防止闪退
    private List<IMStruct002> targetList = new LinkedList<>();
    private ChatListManager chatListManager = new ChatListManager();
    private ImageView iv_chat_add;
    private LinearLayout llMenu;
    //    private ImageLoader imageLoader;
//    private DisplayImageOptions options;
    private TextView tvCount;
    private GroupRootBean bean;

    //聊天权限String
    private String current_Chat_permissionType = "";
    private String current_Chat_permissionContent = "";
    //消息发送管理
    private ChatMessageSendManager chatMessageSendManager = new ChatMessageSendManager(this);

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_chat_add) {
            Toast.makeText(this, ResStringUtil.getString(R.string.wrchatview_group_chat_button), Toast.LENGTH_LONG).show();
        } else {
        }
    }

    private static class MessageHandler extends Handler {
        private WeakReference<ChatActivity> weakReference;
        private long endTime;

        public MessageHandler(ChatActivity activity) {
            weakReference = new WeakReference<ChatActivity>(activity);
        }

        @Override
        public synchronized void handleMessage(Message msg) {
            super.handleMessage(msg);
            ChatActivity activity = weakReference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case 1:
                    if (activity != null && activity.chatAdapter != null) {
                        activity.chatListView.setVisibility(View.GONE);
                        activity.targetList.clear();
                        activity.targetList.addAll(activity.messageList);
                        activity.chatAdapter.notifyDataSetChanged();
                        activity.chatListView.setVisibility(View.VISIBLE);
                        if (activity.chatListView.getLastVisiblePosition() == activity.chatListView.getCount() - 2) {
                            activity.chatListView.setSelection(activity.chatListView.getCount() - 1);
                        } else {
                            Log.i(TAG, "不滚动到最后一条-------");
                        }
                    }
                    break;
                case 11:
//                    if (activity != null && activity.chatAdapter != null) {
//
//                        activity.chatAdapter.notifyDataSetChanged();
//                        activity.chatListView.setSelection(activity.chatListView.getCount() - 1);
//                    }
                    break;
                case 2:
                    activity.targetList.clear();
                    activity.targetList.addAll(activity.messageList);
                    activity.chatAdapter.notifyDataSetChanged();
                    activity.chatListView.setSelection(activity.chatListView.getCount());
                    break;
                case 3:
                    activity.targetList.clear();
                    activity.targetList.addAll(activity.messageList);
                    activity.chatAdapter.notifyDataSetChanged();
                    activity.chatListView.setSelection(msg.arg1 - 1);
                    //3.隐藏显示ProgressBar
                    activity.loadmorePB.setVisibility(View.GONE);
                    break;
                case 4:
                    if (activity.chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                        activity.toChatUserNickTextView.setText(activity.user.getReMark() + ResStringUtil.getString(R.string.network_unavailable));
                    } else {
                        activity.tvCount.setVisibility(View.VISIBLE);
                        activity.tvCount.setText("(" + activity.group.getUsers().size() + ")" + ResStringUtil.getString(R.string.network_unavailable));
                        activity.toChatUserNickTextView.setText(activity.group.getGroupName());
                    }
                    break;
                case 5:
                    if (activity.chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                        activity.toChatUserNickTextView.setText(activity.user.getReMark());
                    } else {
                        activity.tvCount.setVisibility(View.VISIBLE);
                        activity.tvCount.setText("(" + activity.group.getUsers().size() + ")");
                        activity.toChatUserNickTextView.setText(activity.group.getGroupName());
                    }
                    break;
                case 6:
                    //正在输入 chatmessagelistener 会发送这个
                    boolean isInputting = (boolean) msg.obj;
                    String titleText = null;
                    if (isInputting) {
                        activity.toChatUserNickTextView.setText(R.string.wechatview_other_be_inputting);
                        endTime = System.currentTimeMillis() + 6 * 1000;
                        this.sendEmptyMessageDelayed(7, 6 * 1000);
                    } else {
                        if (activity.chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                            activity.toChatUserNickTextView.setText(activity.user.getReMark());
                        }
                    }
                    break;
                case 7:
                    //6中发送的取消正在输入
                    if (System.currentTimeMillis() >= endTime && activity.chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                        activity.toChatUserNickTextView.setText(activity.user.getReMark());
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        id = getIntent().getIntExtra("id", 1);
        chatType = getIntent().getByteExtra("chattype", StructFactory.TO_USER_TYPE_GROUP);
        Log.i(TAG, "onCreate------getIntent()----id:" + id);
        // 获取聊天类型，单聊、群聊，公众号

        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
//            user = WeChatDBManager.getInstance().getOneFriendById(id);
//            if (user.getNickName().equals(String.valueOf(user.getId()))) {
            user = WeChatDBManager.getInstance().getOneUserById(id);
            //  }
        } else if (chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {
            user = new User();
        } else if (chatType == StructFactory.TO_USER_TYPE_GROUP) {
            group = WeChatDBManager.getInstance().getGroupWithUsers(id);
            // JFMessageManager.getInstance().unreadZero(id, chatType);
        }
        if (group != null && chatType == StructFactory.TO_USER_TYPE_GROUP) {
            // 从服务器获取群组联系人
            if (isNetActive()) {
                //如果map中没有此id，说明本地登陆没有请求过群组成员被数据
                if (!SystemInfoService.CHATMAP.containsKey(id)) {
                    try {
                        GetHttpUtil.getGroupUsers(ChatActivity.this, group.getGroupId(), new GetHttpUtil.ReqCallBack<List<User>>() {
                            @Override
                            public void onReqSuccess(List<User> result) {
                                onGetGroupUserSuccess(result, group.getGroupId());
                            }

                            @Override
                            public void onReqFailed(String errorMsg) {

                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        initAttr();
        initView();
        setUpView();
        initShareData(getIntent());
        LogUtils.i(TAG + "onCreate-------------");
        //initImageLoader();
        getChatConfig();
        MessageService.addMessageServiceLoginListener(this);
        MessageService.addMessageServiceNetStateListener(this);
        chatListView.setSelection(chatListView.getCount() - 1);
        if (getIntent().getStringExtra("messageBody") != null) {
            String data = getIntent().getStringExtra("messageBody");
            short subtype = getIntent().getShortExtra("messageType", (short) 0);
            IMStruct002 imStruct002 = new IMStruct002();
            try {
                imStruct002.setBody(data.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            imStruct002.setTime(System.currentTimeMillis());
            imStruct002.setToUserType(Integer.valueOf(chatType).byteValue());
            imStruct002.setToUserId(id);
            imStruct002.setFromUserId(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
            imStruct002.setMessageChildType(subtype);
            JFMessageManager.getInstance().sendMessage(imStruct002);
        }
        EventBus.getDefault().register(this);
    }

//    private void initImageLoader() {
//        // 初始化异步加载图片的类
//        imageLoader = ImageLoader.getInstance();
//        // 设置异步加载图片的配置信息
//        options = ImageUtil.getImageLoaderOptions(R.drawable.default_useravatar);
//    }

    /*titleBar添加快捷按钮*/

    private void getChatConfig() {
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            llMenu.removeAllViews();
        } else {
            ChatConfigUtil.getInstance().getChatConfig(ChatActivity.this, llMenu, group);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // setUpView();

        //！！！启动服务(再onResume中启动，防止这种情况：Activity处于前台，service先于Activity被回收掉)
        startService(new Intent(this, MessageService.class));

        EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(id));
        // 清除通知栏消息
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int requestCode = Integer.valueOf(id + "" + chatType);
        notificationManager.cancel(requestCode);
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
//            user = WeChatDBManager.getInstance().getOneFriendById(id);
//            if (user.getNickName().equals(String.valueOf(user.getId()))) {
            user = WeChatDBManager.getInstance().getOneUserById(id);
            group = null;
            //   }
            toChatUserNickTextView.setText(user.getReMark());
        } else if (chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {
            user = new User();
        } else if (chatType == StructFactory.TO_USER_TYPE_GROUP) {
            user = null;
            group = WeChatDBManager.getInstance().getGroupWithUsers(id);
            if (toChatUserNickTextView != null) {
                tvCount.setVisibility(View.VISIBLE);
                tvCount.setText("(" + group.getUsers().size() + ")");
                toChatUserNickTextView.setText(group.getGroupName());
            }
        }
        //判断是否显示网络不可用
        if (!isNetActive() || !JFMessageManager.isChannelActived()) {
            if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                toChatUserNickTextView.setText(user.getReMark() + ResStringUtil.getString(R.string.network_unavailable));
            } else {
                tvCount.setVisibility(View.VISIBLE);
                tvCount.setText("(" + group.getUsers().size() + ")" + ResStringUtil.getString(R.string.network_unavailable));
                toChatUserNickTextView.setText(group.getGroupName());
            }
        }


//        if (chatAdapter != null) {
//
//            chatAdapter.notifyDataSetChanged();
//        }
    }

    /**
     * 初始化一些属性
     */
    private void initAttr() {
        messageManager = JFMessageManager.getInstance();
        if (messageListener != null) {
            messageManager.removeMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID), messageListener);
        }
        messageListener = new ChatMessageListener(this, id, messageHandler);
        messageManager.addMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID), messageListener);

        chatMessageSendManager.setChatType(chatType);
        chatMessageSendManager.setCurrentChatUserId(id);
        chatMessageSendManager.setPreSendMessageCallback(this);
    }

    /**
     * initView
     */
    protected void initView() {


        chatSenderFragment = (ChatSenderFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_chat_sender);
        chatSenderFragment.setOnClickMessageEditTextListener(ChatActivity.this);
        chatSenderFragment.setOnVoiceRecordListener(ChatActivity.this);
        chatSenderFragment.setSendMessageCallback(ChatActivity.this);
        chatSenderFragment.setPreSendMessageCallback(this);
        onTouchListViewListener = chatSenderFragment;
        chatSenderFragment.setOnTouchListViewListener(onTouchListViewListener);


        recordingContainer = findViewById(R.id.recording_container);
        micImage = (ImageView) findViewById(R.id.mic_image);
        recordingHint = (TextView) findViewById(R.id.recording_hint);
        chatListView = (ChatListView) findViewById(R.id.list);
        loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more);
        toChatUserNickTextView = ((TextView) findViewById(R.id.name));

        iv_setting = (ImageView) this.findViewById(R.id.iv_setting);
        iv_setting_group = (ImageView) this.findViewById(R.id.iv_setting_group);
        iv_chat_add = (ImageView) this.findViewById(R.id.iv_chat_add);
        llMenu = (LinearLayout) findViewById(R.id.ll_chat_menu);
        tvCount = (TextView) findViewById(R.id.group_count);
        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {// 单聊
            iv_setting.setVisibility(View.VISIBLE);
            iv_chat_add.setVisibility(View.GONE);
            iv_setting_group.setVisibility(View.GONE);
            iv_setting.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ChatActivity.this,
                            ChatSingleSettingActivity.class);
                    intent.putExtra("id", id);
                    intent.putExtra("chattype", chatType);
                    startActivity(intent);
                }

            });

            /*****************增加聊天权限控制************************/
            String chat_permission = EnvironmentVariable.getProperty("chatpermission", "");
            if (!chat_permission.equals("")) {
                JSONObject chat_permissionJson = null;
                try {
                    chat_permissionJson = new JSONObject(chat_permission);
                    JSONArray chat_permissionJsonArray = chat_permissionJson.getJSONArray("chatPermission");

                    //JsonObject chat_permissionJson = new JsonParser().parse(chat_permission).getAsJsonObject();
                    //JsonArray chat_permissionJsonArray = chat_permissionJson.getAsJsonArray("chatPermission");
                    for (int i = 0; i < chat_permissionJsonArray.length(); i++) {
                        JSONObject jsonObject = (JSONObject) chat_permissionJsonArray.get(i);
                        String userID = jsonObject.getString("userID");
                        if (userID.equals(id + "")) {
                            current_Chat_permissionType = jsonObject.getString("type");
                            current_Chat_permissionContent = jsonObject.getString("content");
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (current_Chat_permissionType.equals("0")) {
//                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();  //Activity中
//                    if (chatSenderFragment != null) {
//                        transaction.hide(chatSenderFragment);
//                    }
                    LinearLayout fragment_container_chat_sender = (LinearLayout) findViewById(R.id.fragment_container_chat_sender);
                    fragment_container_chat_sender.setVisibility(View.GONE);
                } else {
                    chatSenderFragment.setchatPermission(current_Chat_permissionContent);
                }


            }
            /*****************增加聊天权限控制************************/

        } else if (chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {// 公众号
            chatOfficialAccountsSenderFragment = new ChatOfficialAccountsSenderFragment();
            chatOfficialAccountsSenderFragment
                    .setOnOfficialAccountKyeboardClickListener(this);
            chatSenderFragment.setOnOfficialAccountKyeboardClickListener(this);
            chatOfficialAccountsSenderFragment.setSendMessageCallback(this);
            FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                    .beginTransaction().add(
                            R.id.fragment_container_chat_sender,
                            chatOfficialAccountsSenderFragment,
                            "PublicChatOfficialAccountsSenderFragment");
            fragmentTransaction.hide(chatSenderFragment);
            fragmentTransaction.commit();
            iv_setting.setVisibility(View.VISIBLE);
            iv_chat_add.setVisibility(View.GONE);
            iv_setting_group.setVisibility(View.GONE);
            iv_setting.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(ChatActivity.this,
                            PublicNumerInfoActivity.class);
                    intent.putExtra("id", group.getGroupId());
                    intent.putExtra("chattype", chatType);
                    //startActivity(intent);
                }

            });

        } else {
            iv_setting.setVisibility(View.GONE);
//            iv_chat_add.setVisibility(View.VISIBLE);
            iv_setting_group.setVisibility(View.VISIBLE);
            iv_chat_add.setOnClickListener(this);
            iv_setting_group.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ChatActivity.this,
                            ChatGroupSettingActivity.class);
                    intent.putExtra("id", id);
                    intent.putExtra("chattype", chatType);
                    startActivity(intent);
                }

            });
        }
    }


    @SuppressWarnings("deprecation")
    private void setUpView() {
        activityInstance = this;
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) { // 单聊或者公众号
            toUserNick = user.getReMark();
            toChatUserNickTextView.setText(toUserNick);
            tvCount.setVisibility(View.GONE);
            Log.i(TAG, "toChatUsername:" + chatType);
        } else if (chatType == StructFactory.TO_USER_TYPE_OFFICIAL_ACCOUNT) {
            toChatUserNickTextView.setText(getIntent().getStringExtra("nickName"));
            tvCount.setVisibility(View.GONE);
        } else {
            // findViewById(R.id.container_video_call).setVisibility(View.GONE);
            //  findViewById(R.id.container_voice_call).setVisibility(View.GONE);
            //显示群聊名及人数
            tvCount.setVisibility(View.VISIBLE);
            tvCount.setText("(" + group.getUsers().size() + ")");
            toChatUserNickTextView.setText(group.getGroupName());
        }

        messageList = JFMessageManager.getInstance().getMessageList(id, chatType);

        // TODO 获取历史消息
        if (messageList.size() == 0) {
            List<IMStruct002> historyImStruct002s = chatListManager.getHistoryMessage(chatType, user, messageManager, group, null, 20, null);
        }
        // int unReadCount = JFMessageManager.getInstance().getUnReadCount(id, chatType);
        // int tempCount = 0;
        //if(unReadCount>0){
        for (int i = messageList.size() - 1; i >= 0; i--) {
            if (messageList.get(i).getFromUserId() != Integer.valueOf(EnvironmentVariable
                    .getProperty(Constants.CHAT_USER_ID))
                    && messageList.get(i).getState() != IMStruct002.MESSAGE_STATE_READ
                    && messageList.get(i).getToUserType() != StructFactory.TO_USER_TYPE_GROUP
                    && messageList.get(i).getReadState() != IMStruct002.MESSAGE_STATE_READ
                    ) {
                JFMessageManager.getInstance().sendReadMessage(messageList.get(i));
                //tempCount += 1;
            } else {
                if (messageList.get(i).getToUserType() == StructFactory.TO_USER_TYPE_GROUP) {

                    // JFMessageManager.getInstance().markedAsRead(messageList.get(i));

                }
            }
        }
        setupChatListView();
    }

    private void setupChatListView() {
        targetList.clear();
        targetList.addAll(messageList);
        chatAdapter = new ChatAdapter(this, chatListView, targetList);
        chatListView.setAdapter(chatAdapter);
        chatListView.setSelection(chatListView.getCount() - 1);
        //Touch监听
        chatListView.setOnTouchListener(new ChatListViewOnTouchListener());
    }

    /**
     * 返回
     *
     * @param view
     */
    @Override
    public void back(View view) {
        //在onBackPressed（）中保存输入框中的草稿，所以在此处不调用finish（）
        onBackPressed();
    }

    @Override
    public void sendMessage(IMStruct002 struct002) {
        try {
            if (struct002 != null) {
                struct002.setToUserId(id);
                struct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
                //byte s = 3;
                struct002.setToUserType(chatType);
                boolean b = messageManager.sendMessage(struct002);

                messageHandler.sendEmptyMessage(2);
//                chatAdapter.notifyDataSetChanged();
//                chatListView.setSelection(chatListView.getCount() - 1);

//                messageHandler.sendEmptyMessage(11);
//                // FIXME 测试发送文本
//                new AsyncTask<IMStruct002, Integer, String>() {
//
//                    @Override
//                    protected String doInBackground(IMStruct002... params) {
//                        try {
//                            IMStruct002 struct002 = params[0];
//                            struct002.setToUserType(chatType);
//                            boolean b = messageManager.sendMessage(struct002);
//                            Log.i(TAG, "发送 ------ sendMessage:" + struct002.toString());
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        return null;
//                    }
//                }.execute(struct002);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void preSendMessage(IMStruct002 struct002) {
        if (struct002 != null) {
            struct002.setToUserId(id);
            struct002.setFromUserId(Integer.parseInt(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
            struct002.setToUserType(chatType);
            struct002.putExtra("progress", 0);
            struct002.putExtra("startUploadTime", System.currentTimeMillis());
            messageManager.preSendMessage(struct002);
            messageHandler.sendEmptyMessage(2);
//            chatAdapter.notifyDataSetChanged();
//            chatListView.setSelection(chatListView.getCount() - 1);
        }
    }

    @Override
    public void updateProgress(IMStruct002 struct002, double percent) {
        if (percent == -1.0d) {
            JFMessageManager.getInstance().updateMessage(struct002);
        }
        chatAdapter.notifyDataSetChanged();
    }

    @Override
    public void sendPreMessage(final IMStruct002 struct002) {
        if (struct002 != null) {
            messageManager.sendPreMessage(struct002);

            Log.i(TAG, "发送 ------ sendPreMessage:" + struct002.toString());

//            new AsyncTask<IMStruct002, Integer, String>() {
//                @Override
//                protected String doInBackground(IMStruct002... params) {
//                    try {
//                        messageManager.sendPreMessage(struct002);
//                        Log.i(TAG, "发送 ------ sendPreMessage:" + struct002.toString());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    return null;
//                }
//            }.execute(struct002);
        }
    }

    @Override
    public void onRecording(int musicalScale) {
        micImage.setImageDrawable(ChatVoiceRecordAnimManager.getMicImages(ChatActivity.this)[musicalScale]);
    }

    @Override
    public void onRecorderButtonTouchDown(View v) {
        recordingContainer.setVisibility(View.VISIBLE);
        recordingHint.setText(getString(R.string.move_up_to_cancel));
        recordingHint.setBackgroundColor(Color.TRANSPARENT);
    }

    @Override
    public void onRecorderButtonTouchMove(View v, boolean isCancleRecord) {
        if (isCancleRecord) {
            recordingHint.setText(getString(R.string.release_to_cancel));
            recordingHint
                    .setBackgroundResource(R.drawable.recording_text_hint_bg);
        } else {
            recordingHint.setText(getString(R.string.move_up_to_cancel));
            recordingHint.setBackgroundColor(Color.TRANSPARENT);
        }

    }

    @Override
    public void onRecorderButtonTouchUp(View v) {
        recordingContainer.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onRecorderButtonTouchCancle(View v) {
        recordingContainer.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClickMessageEditText(View v) {
        chatListView.setSelection(chatListView.getCount() - 1);
    }

    @Override
    public void onOfficialAccountKyeboardClick(View v,
                                               boolean isClickFromOfficialAccountView) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        if (chatSenderFragment.isVisible()) {
            fragmentTransaction.hide(chatSenderFragment);
            fragmentTransaction.show(chatOfficialAccountsSenderFragment);
        } else {
            fragmentTransaction.hide(chatOfficialAccountsSenderFragment);
            fragmentTransaction.show(chatSenderFragment);
        }
        fragmentTransaction.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, TAG + "-----------requestCode:" + requestCode + ",resultCode" + resultCode);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        id = intent.getIntExtra("id", 1);
        EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(id));
        chatType = intent.getByteExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
        JFMessageManager.getInstance().unreadZero(id, chatType);
        if (chatType == StructFactory.TO_USER_TYPE_GROUP) {
            group = WeChatDBManager.getInstance().getGroupWithUsers(id);
        } else if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            user = WeChatDBManager.getInstance().getOneUserById(id);
        }
        initAttr();
        initView();
        setUpView();
        initShareData(getIntent());
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "onDestroy");
        EventBus.getDefault().unregister(this);
//        DownloadManager.getInstance().cancelTask();
        if (messageListener != null) {
            messageManager.removeMessageListener(EnvironmentVariable.getProperty(CHAT_USER_ID), messageListener);
        }
        MessageService.removeMessageServiceLoginListener(this);
        MessageService.removeMessageServiceNetStateListener(this);
        //如果可以，请在chatListManager中释放资源
        chatListManager.release(activityInstance);
        activityInstance = null;
        chatAdapter.removeDownLoadListener();
        ChatVoicePlayClickListener.currentPlayListener = null;
//        chatAdapter = null;
        //取消getChatConfig的网络任务
        ChatConfigUtil.getInstance().cancleRequest(ChatActivity.this);
        super.onDestroy();

        ChatConfigUtil.getInstance().cancleRequest(ChatActivity.this);

    }

    @Override
    public void onBackPressed() {
        if (isTaskRoot()) {
            try {
                String className = getResources().getString(R.string.from_group_backto_first);
                Class clazz = Class.forName(className);
                Intent myIntent = new Intent(this, clazz);
                startActivity(myIntent);
                finish();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    //撤回消息刷新界面消息事件
    public void refreshListData(NotifyChatUIRefreshEvent event) {
        if (event.getNotifyType() == NotifyChatUIRefreshEvent.TYPE_DEFAULT) {
            if (event.getParamMap().containsKey("fromUserId")){
                int fromUserId = (int) event.getParamMap().get("fromUserId");
                byte type = (byte) event.getParamMap().get("chatType");
                if (fromUserId == id && chatType == type) {
                    //是当前聊天人的消息才会刷新界面
                    chatAdapter.notifyDataSetChanged();
                }
            }else{
                chatAdapter.notifyDataSetChanged();
            }
        } else if (event.getNotifyType() == NotifyChatUIRefreshEvent.TYPE_EXIT
                && event.getChatType() == chatType && event.getChatUserId() == id) {
            onBackPressed();
        }
    }

    public void onGetGroupUserSuccess(final List<User> groupUsers, int groupId) {
        Log.i(TAG, "--请求群组联系人成功--");
        SystemInfoService.CHATMAP.put(id, true);
        Disposable disposable = Observable.create(new ObservableOnSubscribe<Group>() {

            @Override
            public void subscribe(ObservableEmitter<Group> emitter) throws Exception {
                Log.e(TAG, "Observable thread is : " + Thread.currentThread().getName());
                group = WeChatDBManager.getInstance().getGroupWithUsers(id);
                emitter.onNext(group);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Group>() {
            @Override
            public void accept(final Group group) throws Exception {
                Log.e(TAG, "After observeOn(io)，Current thread is " + Thread.currentThread().getName());

                if (group.getUsers().size() < groupUsers.size()) {
                    group.setUsers(groupUsers);
                }
                tvCount.setVisibility(View.VISIBLE);
                tvCount.setText("(" + group.getUsers().size() + ")");
                toChatUserNickTextView.setText(group.getGroupName());
                final String avatar = group.getAvatar();
                //如果群头像是网络图片就不自动生成了
                if (GroupAvatarUtil.isServerAvatar(avatar)) {
                    return;
                }
                File file = new File(group.getAvatar());

                if (avatar.equals("") || !file.exists()) {
                    List<String> avatars = new ArrayList<>();
                    for (User user : groupUsers) {
                        if (user.getId() == group.getCreateId()) {
                            avatars.add(0, user.getAvatar());
                        } else {
                            avatars.add(user.getAvatar());
                        }
                    }
                    final GroupAvatarHelper helper = new GroupAvatarHelper(ChatActivity.this);
                    helper.getAvatar(group, avatars, new GroupAvatarHelper.LoadImageListener() {
                        @Override
                        public void loadImageComplete(NineGridImageView view) {
                            if (view == null) {
                                return;
                            }
                            String path = helper.getAvatarPath(view);
                            group.setAvatar(path);
                            WeChatDBManager.getInstance().insertOrUpdateGroup(group);
                        }
                    });
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        });

        //  group = WeChatDBManager.getInstance().getGroupWithUsers(id);

    }

    @Override
    public void netStateChange(int net_state) {
        Log.i(TAG, "netStateChange--监听网络状态--" + net_state);
        if (net_state == 0) {
            // rl_error_item.setVisibility(View.VISIBLE);
            Message message = new Message();
            message.what = 4;
            this.messageHandler.sendMessage(message);
        } else {
            //rl_error_item.setVisibility(View.GONE);
            Message message = new Message();
            message.what = 5;
            this.messageHandler.sendMessage(message);
        }
    }

    //处理网络监听状态handle
  /*  Handler netStateChangeHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (chatType == StructFactory.TO_USER_TYPE_PERSONAL)
                        toChatUserNickTextView.setText(user.getReMark() + "(网络不可用)");
                    else {
                        tvCount.setVisibility(View.VISIBLE);
                        tvCount.setText("(" + group.getUsers().size() + ")" + "(网络不可用)");
                        toChatUserNickTextView.setText(group.getGroupName());
                    }
                    break;
                case 1:
                    if (chatType == StructFactory.TO_USER_TYPE_PERSONAL)
                        toChatUserNickTextView.setText(user.getReMark());
                    else {
                        tvCount.setVisibility(View.VISIBLE);
                        tvCount.setText("(" + group.getUsers().size() + ")");
                        toChatUserNickTextView.setText(group.getGroupName());
                    }

                    break;
            }
            super.handleMessage(msg);
        }
    };*/

    //监听tcp是否可用事件
    @Override
    public void onLoginSuccess() {
        Message message = new Message();
        message.what = 5;

        this.messageHandler.sendMessage(message);
    }

    @Override
    public void onLoginFail(String errorMsg) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        //清除掉保存的未读@消息提醒
        //TextFormatMessageUtil.clearMentionHintEV(id+"", chatType+"");
        JFMessageManager.getInstance().clearAtMe(id, chatType);
        //使用id+type作为保存草稿的key
        String unfinishedText = id + "" + chatType;
        //将草稿保存到EV中(没有@人才存草稿)
        if (!TextFormatMessageUtil.editTextHasAt(((EditText) chatSenderFragment.getView().findViewById(R.id.et_sendmessage)).getText())) {
            EnvironmentVariable.setProperty(unfinishedText,
                    ((EditText) chatSenderFragment.getView().findViewById(R.id.et_sendmessage)).getText().toString());
        }
        chatListManager.clearunReadCount(id, chatType);
        EventBus.getDefault().post(new UpdateBadgeViewEvent(id + "", chatType));

    }

    /**
     * 初始化分享的数据
     */

    private void initShareData(Intent intent) {
        if (intent.hasExtra("share")) {
            if (intent.hasExtra("shareImages")) {
                ArrayList<String> shareImageList = intent.getStringArrayListExtra("shareImages");
                if (shareImageList != null) {
                    chatMessageSendManager.sendPicture(shareImageList, false);
                }
            }
        }
    }

    private class ChatListViewOnTouchListener implements View.OnTouchListener {

        private long chatListViewTouchMoveTime;
        private int chatListViewDownY;
        private int chatListViewDownYSlop;

        public ChatListViewOnTouchListener() {
            chatListViewDownYSlop = (int) (5 * getResources().getDisplayMetrics().density);
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (onTouchListViewListener != null) {
                        onTouchListViewListener.onTouchListView();
                    }
                    chatListViewDownY = (int) event.getY();
                    chatListManager.hideKeyboard(ChatActivity.this);
                    break;
                case MotionEvent.ACTION_UP:
                    v.performClick();
                    break;
                case MotionEvent.ACTION_MOVE:
                    //触发下拉事件，每0.5秒执行一次
                    if (event.getY() - chatListViewDownY > chatListViewDownYSlop && System.currentTimeMillis() - chatListViewTouchMoveTime > 500) {
                        Log.e("==", "=====每0.5秒执行一次：" + event.getAction());
                        tryLoadHistoryMessage();
                        chatListViewTouchMoveTime = System.currentTimeMillis();
                    }
                    break;

                default:
                    break;
            }
            return false;
        }
    }

    private void tryLoadHistoryMessage() {
        View topView = chatListView.getChildAt(0);
        if (chatListView.getFirstVisiblePosition() == 0 && topView != null && topView.getTop() == 0 && loadmorePB.getVisibility() != View.VISIBLE) {
            Log.e("==", "加载更多--onScroll==firstVisibleItem：" + topView.getTop());
            //1.先显示ProgressBar
            loadmorePB.setVisibility(View.VISIBLE);
            Disposable disposable = Observable.create(new ObservableOnSubscribe<List<IMStruct002>>() {
                @Override
                public void subscribe(ObservableEmitter<List<IMStruct002>> emitter) throws Exception {
                    List<IMStruct002> historyImStruct002s = chatListManager.getHistoryMessage(chatType, user, messageManager, group, messageList.get(0).getMessageID(), 20, null);
                    chatListManager.solveUnRead(messageList, historyImStruct002s);
                    emitter.onNext(historyImStruct002s);
                    emitter.onComplete();
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<IMStruct002>>() {
                @Override
                public void accept(List<IMStruct002> imStruct002s) throws Exception {
                    Message message = messageHandler.obtainMessage();
                    message.what = 3;
                    message.arg1 = imStruct002s.size();
                    messageHandler.sendMessage(message);
//                    chatAdapter.notifyDataSetChanged();
//                    int historyMessageCount = imStruct002s.size();
//                    chatListView.setSelection(historyMessageCount - 1);
//                    //3.隐藏显示ProgressBar
//                    loadmorePB.setVisibility(View.GONE);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {

                }
            });
//            new AsyncTask() {
//
//                @Override
//                protected List<IMStruct002> doInBackground(String... params) {
//                    List<IMStruct002> historyImStruct002s = chatListManager.getHistoryMessage(chatType, user, messageManager, group, messageList.get(0).getMessageID(), 20, null);
//                    chatListManager.solveUnRead(messageList, historyImStruct002s);
//                    return historyImStruct002s;
//                }
//
//                @Override
//                protected void onPostExecute(List<IMStruct002> imStruct002s) {
//                    super.onPostExecute(imStruct002s);
//                    chatAdapter.notifyDataSetChanged();
//                    int historyMessageCount = imStruct002s.size();
//                    chatListView.setSelection(historyMessageCount - 1);
//                    //3.隐藏显示ProgressBar
//                    loadmorePB.setVisibility(View.GONE);
//                }
//            }.executeOnExecutor(Executors.newCachedThreadPool());

        }
    }
}
